import { AuthService } from './../auth.service';
import { Router, NavigationExtras } from '@angular/router';
import { Component, OnInit } from '@angular/core';
/**
 * 利用身份验证服务来帮助登入登出
 *
 * @export
 * @class LoginComponent
 * @implements {OnInit}
 */
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})

export class LoginComponent implements OnInit {

  // 用来记录登陆情况
  message!: string ;

  constructor(private router:Router,protected authService: AuthService) {
      //初始化页面，到底是登录还是等出
      this.message = this.getMessage()
  }

  // 打印登入还是登出
  getMessage(){
     return 'Status: Logged' + (this.authService.isLoginedIn ? 'in' : 'out')
  }

  ngOnInit(): void {
  }

  logIn(){
     this.message = 'Trying to login...'

     this.authService.login().subscribe(() => {
         this.message = this.getMessage()

         // 已是登录状态，那么就重定向到登陆后的首页
         if(this.authService.isLoginedIn){

            const redirectUrl = '/admin'

            const navigationExtras: NavigationExtras = {
              queryParamsHandling: 'preserve',
              preserveFragment: true
          }

            this.router.navigate([redirectUrl],navigationExtras)
         }
     })
  }


  logOut(){
     this.authService.logout()
     this.message = this.getMessage()
  }



}
